package org.hdax.dm.rest.service;


import org.hda.dm.utils.DateUtil;
import org.hdax.dm.dao.entitydao.DmItemDao;
import org.hdax.dm.entity.item.DmItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RestItemService {
    @Autowired
    private DmItemDao dmItemDao;

    @PostMapping(path = "/findByDmitem")
    public List<DmItem> findByDmitem(@RequestParam(name = "offset", defaultValue = "0") Integer offset, @RequestParam(name = "limit", defaultValue = "5") Integer limit, @RequestBody DmItem dmItem) {
        Pageable pageable = PageRequest.of(offset, limit);
        return dmItemDao.findAll(where(dmItem), pageable).getContent();
    }

    @PostMapping(path = "/findById")
    public DmItem findById(@RequestParam("id") Integer id) {
        return dmItemDao.findById(id).get();
    }

    public Specification<DmItem> where(DmItem dmItem) {
        return new Specification<DmItem>() {
            @Override
            public Predicate toPredicate(Root<DmItem> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (dmItem != null) {
                    if (dmItem.getItemType1Id() != null && dmItem.getItemType1Id() >= 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("itemType1Id").as(Integer.class), dmItem.getItemType1Id()));
                    }
                    if (dmItem.getIsBanner() != null && dmItem.getIsBanner() >= 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("isBanner").as(Integer.class), dmItem.getIsBanner()));
                    }
                    if (dmItem.getIsRecommend() != null && dmItem.getIsRecommend() >= 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("isRecommend").as(Integer.class), dmItem.getIsRecommend()));
                    }
                    if (dmItem.getIsRecommend() != null && dmItem.getIsRecommend() == 1 && dmItem.getStartTime() != null) {
                        predicateList.add(criteriaBuilder.between(root.get("startTime").as(String.class), DateUtil.returnToday(), DateUtil.returnTomorrow()));
                    }
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            }
        };
    }
}
